package secondary_classes;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;


/**
 * @author Rohit
 *
 */
public class CsvFileReader {
	private ArrayList<ArrayList<String>> items;
	private int size;
	
	
	/**
	 * @param filename Filename of a CSV file to be read
	 * @throws Exception use {@link Exception#getMessage()} to get a more detailed explanation
	 */
	public CsvFileReader(String filename) throws Exception {
		this.items = new ArrayList<ArrayList<String>>();
		
		File file;
		BufferedReader csvIn = null;
		String line;
		
		file = new File(filename);
		//System.out.println(file.getAbsolutePath());
		try {
			csvIn = new BufferedReader(new FileReader(file.getAbsoluteFile()));
		} catch (FileNotFoundException e) {
			throw new Exception("Could not find file: " + filename);
		}
	
		// create an array of all the tokens plus delimiters
		try {
			while((line = csvIn.readLine()) != null) {
				StringTokenizer st = new StringTokenizer(line, ",", true);
				ArrayList<String> thisLine = new ArrayList<String>();
				while (st.hasMoreTokens()) {
					thisLine.add(st.nextToken()); //get next token and store it in the array
					this.size++;
				}
//				if (line.endsWith(",")) {
					thisLine.add(",");
//				}

				items.add(thisLine);
			}
		} catch (IOException e) {
			throw new Exception("Invalid CSV file: " + filename);
		}
		
		// remove delimiters, leaving a blank where there are consecutive delimiters
		int j = 0;
		boolean consecutive;
		for (int i = 0; i < items.size(); i++) {
			consecutive = false;
			j = 0;
			while (j < items.get(i).size()) {
				if (items.get(i).get(j).equals(",")) {
					if (consecutive) {
						items.get(i).set(j, "");
						j++;
					} else {
						items.get(i).remove(j);
						consecutive = true;
					}
				} else {
					consecutive = false;
					j++;
				}
			}
		}
//		System.out.print("");
	}
	
	public int getNumLines() {
		return this.items.size();
	}
	
//	public int getSize() {
//		return this.size;
//	}
	
	public String getItem(int line, int i) {
		return items.get(line).get(i);
	}
	
	public ArrayList<String> getLine(int line) {
		return items.get(line);
	}
}
